#include "DXMesh.h"
#include "DXEngine.h"
#include "DXTexture.h"
#include <dxerr.h>


CDXMesh::~CDXMesh()
{
	ReleaseCOM(m_pMesh);
	freeTextures();
}

void CDXMesh::freeTextures()
{
	while (!m_pTextures.empty())
	{
		delete (m_pTextures[0]);
		m_pTextures.erase(m_pTextures.begin());
	}
}


void CDXMesh::load(const char *szFileName)
{
	LPD3DXMATERIAL		tempMaterials = NULL;
	DWORD				dwNumMaterials = 0;
	LPD3DXBUFFER		pMaterials = NULL;
	
	assert(CDXEngine::getInstance()->getD3DDevice() != NULL);
	assert(szFileName != NULL);
	
	HR( D3DXLoadMeshFromX(	szFileName,
							D3DXMESH_MANAGED,
							CDXEngine::getInstance()->getD3DDevice(),
							NULL,
							&pMaterials,
							NULL,
							&dwNumMaterials,
							&m_pMesh ));
	assert(dwNumMaterials != NULL);
	tempMaterials = (LPD3DXMATERIAL)pMaterials->GetBufferPointer();
	for (unsigned i = 0; i < dwNumMaterials; ++i)
	{
		CDXTexture* newTexture = new CDXTexture;

		newTexture->init(tempMaterials[i]);
		m_pTextures.push_back(newTexture);
	}
	pMaterials->Release();
}

void CDXMesh::render()
{
	assert(m_pMesh != NULL);

	for (unsigned int i = 0; i < m_pTextures.size(); ++i)
	{
		m_pTextures[i]->render();
		HR(m_pMesh->DrawSubset(i));
	}
}



HRESULT CDXMesh::loadTexture(const char* pTexFile)
{
	D3DMATERIAL9	material;
	CDXTexture		*newTexture = new CDXTexture;
	
	material.Emissive.a = 1.0;
	material.Emissive.r = 1.0f;
	material.Emissive.g = 1.0f;
	material.Emissive.b = 1.0f;	
	material.Ambient = material.Emissive;
	material.Diffuse = material.Emissive;
	newTexture->setMaterialInfo(material);
	if (newTexture->extractTextureInfo(pTexFile) == false)
	{
		delete newTexture;
		return S_FALSE;
	}
	m_pTextures.push_back(newTexture);
	return S_OK;
}
